//: [Previous](@previous)

/*:
 [58. 螺旋举证](https://leetcode-cn.com/problems/spiral-matrix-ii/)

 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

 输入：n = 3
 输出：[[1,2,3],[8,9,4],[7,6,5]]
 */

import Foundation


func generateMatrix(_ n: Int) -> [[Int]] {
    var matrixs: [[Int]] = Array(repeating: Array(repeating: 1, count: n), count: n)
    var left = 0, right = n - 1, top = 0, bottom = n - 1
    var num = 1, tar = n * n
    while true {
        // left -> right
        for i in left...right {
            matrixs[top][i] = num
            num += 1
        }
        if num > tar { break }
        top += 1
        // top -> bottom
        for i in top...bottom {
            matrixs[i][right] = num
            num += 1
        }
        if num > tar { break }
        right -= 1
        // right -> left
        for i in (left...right).reversed() {
            matrixs[bottom][i] = num
            num += 1
        }
        if num > tar { break }
        bottom -= 1
        for i in (top...bottom).reversed() {
            matrixs[i][left] = num
            num += 1
        }
        if num > tar { break }
        left += 1
    }
    return matrixs
}

print(generateMatrix(1))
print(generateMatrix(3))
print(generateMatrix(6))

//: [Next](@next)
